type ScrollBarType = {
  wrapRef: HTMLElement;
  setScrollTop: (num: number) => void;
};
class ScrollUtil {
  private scrollBar: ScrollBarType;
  lastAllHeight: number = 0; //用于聊天窗口 当聊天发送来时自适应到底部
  lastScrollTop: number = 0; //上一次滚动时总滚动的距离
  lastScrollLeft: number = 0; //上一次滚动时总滚动的距离
  lastMovingVerLen: number = 0; //上一次垂直方向方向移动的距离 如果是大于0那么向上移动了
  lastMovingHorLen: number = 0; //上一次水平方向移动的距离 如果是大于0 那么向左移动了
  public updateScroll(e: { scrollTop: number; scrollLeft: number }) {
    this.lastMovingVerLen = this.lastScrollTop - e.scrollTop; //
    this.lastMovingHorLen = this.lastScrollLeft - e.scrollLeft;
    this.lastScrollTop = e.scrollTop;
    this.lastScrollLeft = e.scrollLeft;
  }
  public scrollToBottom() {
    let shouldScroll =
      this.scrollBar.wrapRef.children[0].clientHeight -
      this.scrollBar.wrapRef.clientHeight;
    if (shouldScroll > 0) this.scrollBar.setScrollTop(shouldScroll);
    this.lastMovingVerLen = this.lastScrollTop - shouldScroll;
    this.lastScrollTop = shouldScroll;
  }
  public scrollToBottomByCond() {
    //用于聊天窗口 当聊天发送来时自适应到底部
    let containerHeight = this.scrollBar.wrapRef.clientHeight; //scroll容器的高度
    let allHeight = this.scrollBar.wrapRef.children[0].clientHeight; //新的内容的高度
    if (this.lastAllHeight == 0) this.lastAllHeight = allHeight;
    if (allHeight - containerHeight <= 0) return;
    let lastLenToBottom =
      this.lastAllHeight - containerHeight - this.lastScrollTop;
    if (lastLenToBottom < 50) {
      this.scrollToBottom();
    }
    this.lastAllHeight = allHeight;
  }
  public verMovingDir(): "toTop" | "toBottom" | "none" {
    if (this.lastMovingVerLen > 0) return "toTop";
    if (this.lastMovingVerLen < 0) return "toBottom";
    return "none";
  }
  public horMovingDir(): "toLeft" | "toRight" | "none" {
    if (this.lastMovingHorLen > 0) return "toLeft";
    if (this.lastMovingHorLen < 0) return "toRight";
    return "none";
  }
  public heightToBottom() {
    return ScrollUtil.heightToBottom(this.lastScrollTop, this.scrollBar);
  }
  constructor(scrollBar: ScrollBarType) {
    this.scrollBar = scrollBar;
  }

  static heightToBottom(scrollTop: number, scrollBar: ScrollBarType): number {
    //scrollTop为滚动的高度; 当容器触底时 scrollTop+containerHeight=contentHeight
    //如果contentHeight<ContainerHeight 那么说明滚动条内部的元素高度还没有到达滚动区域的最大高度 此时不可以滚动
    //所求值实际上是滚动区域高度+滚动了的距离-元素的总高度 越接近于0 说明越靠近底部 大于0说明 元素总高度小于滚动区域高度 小于0说明 元素总高度大于滚动区域高度+已经滚动的距离
    let containerHeight = scrollBar.wrapRef.clientHeight; //scrollbar容器的高度
    let contentHeight = scrollBar.wrapRef.children[0].clientHeight;
    let distanceToBottom = contentHeight - containerHeight - scrollTop;
    return distanceToBottom;
  }
}
export default ScrollUtil;
